package com.qf.electronic.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.electronic.common.R;
import com.qf.electronic.common.ResponseStatus;
import com.qf.electronic.dto.TowerDto;
import com.qf.electronic.dto.TowerStateDto;
import com.qf.electronic.pojo.Tower;
import com.qf.electronic.service.ITowerService;
import com.qf.electronic.util.IdGenerator;
import com.qf.electronic.vo.TowerVo;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wu
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/tower")
public class TowerController {
    @Autowired
    private ITowerService towerService;

    @Autowired
    private IdGenerator idGenerator;
    @PostMapping
    public R<Boolean> addTower(@Valid @RequestBody Tower tower, BindingResult result){
        if(result.hasFieldErrors()){//如果存在数据校验错误
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        tower.setId(idGenerator.generateId(IdGenerator.TOWER_PREFIX, IdGenerator.TOWER_KEY, 11));
        return R.ok(towerService.save(tower));
    }
    @PutMapping
    public R<Boolean> updateTower(@Valid @RequestBody Tower tower, BindingResult result){
        if(result.hasFieldErrors()){//如果存在数据校验错误
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        return R.ok(towerService.updateById(tower));
    }
    @PutMapping("/state")
    public R<Boolean> changeTowerState(@RequestBody TowerStateDto towerStateDto){
        UpdateWrapper<Tower> wrapper = new UpdateWrapper<>();
        wrapper.set("state", towerStateDto.getState());
        wrapper.in("id", towerStateDto.getTowerIds());
        return R.ok(towerService.update(wrapper));
    }
    @DeleteMapping
    public R<Boolean> deleteTowers(@RequestParam("towerIds")List<String> towerIds){
        return R.ok(towerService.removeByIds(towerIds));
    }
    @GetMapping
    public R<Page<TowerVo>> searchTowers(TowerDto towerDto){
        return R.ok(towerService.searchTowers(towerDto));
    }
}

